﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class MainForm : Form
    {
        private bool _isSearching;
        private FileEnumerator _enumerator;
        private Comparer _comparer;
        private CompareOperationState _state;

        public MainForm()
        {
            InitializeComponent();
        }

// ReSharper disable InconsistentNaming
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (_state.EnumerationState == CompareOperationState.State.Started || _state.CompareState == CompareOperationState.State.Started)
            {
                var fileCount = _state.ItemList.Count;
                if (fileCount == 0) continue;

                var filesProcessed = _comparer.FilesCompared;

                SetControlPropertyValue(progressLabel, "Text", string.Format("Processed {0}/{1}", filesProcessed, fileCount));

                var progress = 100 * filesProcessed / fileCount;

                SetControlPropertyValue(progressBar, "Maximum", fileCount);
                SetControlPropertyValue(progressBar, "Value", filesProcessed);

                backgroundWorker1.ReportProgress(progress);    
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            // do stuff here IF u want
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            var itemCount = _state.ItemList.Count;
            var itemProcessed = _comparer.FilesCompared;
            
            SetControlPropertyValue(progressBar, "Maximum", itemCount);
            SetControlPropertyValue(progressBar, "Value", itemProcessed);
            SetControlPropertyValue(progressLabel, "Text", string.Format("Processed {0}/{1}", itemProcessed, itemCount));

            MessageBox.Show(string.Format("Processed {0}/{1}", itemProcessed, itemCount));

            // test
            Debug.WriteLine("{0} has {1} duplicates",
                    _state.ItemList[0].Filename, _state.ItemList[0].Duplicates.Count);
            for (var i = 0; i < _state.ItemList[0].Duplicates.Count; i++)
            {
                Debug.WriteLine("{0} equal with {1}",
                    _state.ItemList[0].Filename, _state.ItemList[_state.ItemList[0].Duplicates[i]].Filename);
            }
            // end test

            _isSearching = false;
            powerButton.Text = @"Start";
        }

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            removeFolderButton.Enabled = searchFoldersListBox.SelectedIndices.Count > 0;
        }

        private void addFolderButton_Click(object sender, EventArgs e)
        {
            var dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                var folder = dlg.SelectedPath;
                var index = searchFoldersListBox.Items.Add(folder);
                searchFoldersListBox.SetItemChecked(index, true);
            }
        }

        private void removeFolderButton_Click(object sender, EventArgs e)
        {
            foreach (var item in searchFoldersListBox.SelectedItems)
            {
                searchFoldersListBox.Items.Remove(item);
            }
        }

        private void powerButton_Click(object sender, EventArgs e)
        {
            if (_isSearching)
            {
                powerButton.Text = @"Start";
                _isSearching = false;
            }
            else
            {
                powerButton.Text = @"Stop";

                _state = new CompareOperationState();

                var folders = searchFoldersListBox.CheckedItems.OfType<string>().ToArray();
                _enumerator = new FileEnumerator(folders, _state);

                var thread = new Thread(_enumerator.EnumerateFiles);
                thread.Start();

                _comparer = new Comparer(_state);
                var thread2 = new Thread(_comparer.Process);
                thread2.Start();

                backgroundWorker1.RunWorkerAsync();
                _isSearching = true;
            }
        }

// ReSharper restore InconsistentNaming

        delegate void SetControlValueCallback(Control oControl, string propName, object propValue);

        private void SetControlPropertyValue(Control oControl, string propName, object propValue)
        {
            if (oControl.InvokeRequired)
            {
                SetControlValueCallback d = SetControlPropertyValue;
                oControl.Invoke(d, new[] { oControl, propName, propValue });
            }
            else
            {
                var t = oControl.GetType();
                var props = t.GetProperties();
                foreach (var p in props.Where(p => p.Name.ToUpper() == propName.ToUpper())) p.SetValue(oControl, propValue, null);
            }
        }

        private void MainFormLoad(object sender, EventArgs e)
        {
            
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void progressBar_Click(object sender, EventArgs e)
        {

        }

        private void progressLabel_Click(object sender, EventArgs e)
        {

        }

        
    }
}
